<template>
  <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" v-loading="loading">
    <!-- 标题 -->
    <el-form-item label="公告标题" prop="releaseTitle">
      <el-input v-model="formData.releaseTitle" placeholder="请输入公告标题" />
    </el-form-item>

    <!-- 接收人员 -->
    <el-form-item label="接收人员" prop="receiverType">
      <el-radio-group v-model="formData.receiverType">
        <el-radio label="all" >全体人员</el-radio>
        <el-radio label="specific">指定人员</el-radio>
      </el-radio-group>

      <el-select
          v-if="formData.receiverType === 'specific'"
          v-model="formData.selectedUsers"
          multiple
          placeholder="请选择人员"
          style="width: 140px; margin-top: 10px;margin-left: 10px;"
      >
        <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.username"
            :value="user.id"
        />
      </el-select>
    </el-form-item>

    <!-- 富文本编辑器 -->
    <el-form-item label="公告内容" prop="releaseContent" v-model="formData.releaseContent">
      <div id="editor-container" style="border: 1px solid #ccc"></div>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm" v-if="$hasPermission('crm:system:notice:add')">立即发布</el-button>
      <el-button type="primary" @click="close">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {nextTick, onMounted, onUnmounted, ref,} from 'vue'
import E from 'wangeditor'
import router from "@/router";
import {ElMessage} from "element-plus";
import request from "@/utils/request";

const loading = ref(false)
// 表单引用
const formRef = ref()
// 表单数据
const formData = ref({
  releaseTitle: undefined,
  receiverType:'all',
  selectedUsers: [],
  releaseContent: undefined
})

// 表单验证规则
const formRules = {
  releaseTitle: [{ required: true, message: '请输入公告标题'}],
  releaseContent: [{ required: true, validator: checkContent}]
}

// 自定义内容验证 validator: checkContent
function checkContent(rule, value, callback) {
  if (editor.txt.text().trim() === '') {
    callback(new Error('请输入公告内容'))
  } else {
    callback()
  }
}
// 用户列表（模拟数据）
const userList = ref([])
let editor = null;
// 初始化编辑器
const initEditor = () => {
  if(editor==null){
    editor = new E('#editor-container')
    editor.config.onchange = (html) => {
      formData.value.releaseContent = html
    }
    editor.create()
  }
}
// 查询指定人员列表
const loadUserList = () => {
  request.get('/api/crm/user/select')
    .then(res=>{
      userList.value = res.data;
    })
}

onMounted(() => {
  loadUserList();
  initEditor();
})
// 提交表单
const submitForm = () => {
  loading.value = true
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请正确填写参数')
      loading.value = false;
      return
    }
    let data = {...formData.value}
    request.post('/api/crm/notice/save',data).then( res => {
      ElMessage.success('新增成功')
      console.log(data)
      router.push('/system/notice')
    })
    loading.value = false
  })
}
onUnmounted(() => {
  if (editor) {
    editor.destroy() // 组件卸载时销毁编辑器
    editor = null
  }
})
// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  editor.txt.html('')
}
//返回按钮的方法
const close = () => {
  if(confirm('离开本页面将不会保存您的修改，您确定要离开吗？')){
    resetForm();
    router.push('/system/notice');
  }
}
</script>

<style scoped>

</style>